import { useFrame } from '@react-three/fiber';
import { useEffect, useRef } from 'react';
import { BoxGeometry, LineSegments, Mesh } from 'three';

interface BoxProps {
  position: [number, number, number];
  dimensions: [number, number, number];
  color: string;
  emissive?: string;
  emissiveIntensity?: number;
  metalness?: number;
  roughness?: number;
  wireframe?: boolean;
  opacity?: number;
  rotate?: boolean;
  renderOrder?: number;
}

export function Box({ 
  position, 
  dimensions, 
  color,
  emissive = '#000000',
  emissiveIntensity = 0,
  metalness = 0,
  roughness = 1,
  wireframe = false, 
  opacity = 1,
  rotate = false,
  renderOrder = 0,
}: BoxProps) {
  const meshRef = useRef<Mesh>(null!);
  const edgesRef = useRef<LineSegments>(null!);
  
  useFrame(() => {
    if (meshRef.current && rotate) {
      meshRef.current.rotation.y += 0.005;
      if (edgesRef.current) {
        edgesRef.current.rotation.y += 0.005;
      }
    }
  });

  useEffect(() => {
    if (meshRef.current) {
      meshRef.current.rotation.set(0, 0, 0);
      meshRef.current.renderOrder = renderOrder;
    }
    if (edgesRef.current) {
      edgesRef.current.rotation.set(0, 0, 0);
      edgesRef.current.renderOrder = renderOrder;
    }
  }, [position, renderOrder]);

  // 计算对角线顶点
  const [width, height, depth] = dimensions;
  const w = width / 2;
  const h = height / 2;
  const d = depth / 2;

  return (
    <group position={position}>
      <mesh ref={meshRef} castShadow receiveShadow>
        <boxGeometry args={dimensions} />
        <meshStandardMaterial 
          color={color}
          emissive={emissive}
          emissiveIntensity={emissiveIntensity}
          metalness={metalness}
          roughness={roughness}
          wireframe={wireframe}
          transparent
          opacity={opacity}
        />
      </mesh>
      {/* 永久显示的边框 */}
      <lineSegments ref={edgesRef}>
        <edgesGeometry args={[new BoxGeometry(...dimensions)]} />
        <lineBasicMaterial color="#000000" linewidth={2} />
      </lineSegments>
      
      {wireframe && (
        <>
          {/* 内部网格线 - 垂直 */}
          {Array.from({ length: 4 }).map((_, i) => (
            <lineSegments key={`v${i}`}>
              <bufferGeometry>
                <bufferAttribute
                  attach="attributes-position"
                  count={2}
                  array={new Float32Array([
                    -w + (width/5) * (i + 1), -h, -d,
                    -w + (width/5) * (i + 1), -h,  d
                  ])}
                  itemSize={3}
                />
              </bufferGeometry>
              <lineBasicMaterial color="#666666" transparent opacity={0.5} />
            </lineSegments>
          ))}
        </>
      )}
    </group>
  );
}